package com.farm.view.convertor.impl;

import java.io.File;

import com.farm.view.convertor.FileConvertorInter;
import com.farm.view.model.ViewFileModelInter;
import com.farm.view.model.utils.EncodeUtils;
import com.farm.view.model.utils.FileWriteUtils;
import com.farm.view.task.domain.ConvertTaskFile;

public class TxtToHtmlConvertor implements FileConvertorInter {

	@Override
	public String getKey() {
		return "TXT_TO_HTML";
	}

	@Override
	public String getTitle() {
		return "TXT按编码转为HTML";
	}

	@Override
	public String getNote() {
		return "主动获得txt编码，并依赖编码读取文本字符，解決TXT读取的乱码问题";
	}

	@Override
	public void doConvert(ConvertTaskFile fileInfo, ViewFileModelInter oviewFileModel,
			ViewFileModelInter tviewFileModel) {
		try {
			File ofile = oviewFileModel.getModelFile(fileInfo.getFile(), fileInfo.getExname());
			File tfile = tviewFileModel.getModelFile(fileInfo.getFile(), fileInfo.getExname());
			if (!ofile.exists()) {
				throw new RuntimeException("the file is not exist!");
			}
			String text = FileWriteUtils.readTxtFile(ofile, EncodeUtils.getEncode(ofile.getPath()));
			StringBuffer buffer = new StringBuffer();
			buffer.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
			buffer.append("<html><head>");
			buffer.append("<meta http-equiv=\"CONTENT-TYPE\" content=\"text/html; charset=utf-8\" /> ");
			buffer.append("<title></title>");
			// buffer.append(HtmlUtils.getIncludeCssAndJs());
			buffer.append("</head>");
			buffer.append("<body>");
			buffer.append(text.replaceAll("[\n]+", "<br/>"));
			buffer.append("</body>");
			buffer.append("</html>");
			FileWriteUtils.wirteInfo(tfile, buffer.toString());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
